<template>
  <div class="notice">
    <Header title="通知">
    </Header>
    <div class="mui-content">
      <div id="slider" v-if="!isEmpty(listData)" class="mui-slider mui-fullscreen">
        <div
          id="sliderSegmentedControl"
          class="mui-slider-indicator mui-segmented-control mui-segmented-control-inverted"
        >
          <div class="notice-nav">
            <a
              v-for="(item, index) in nav_list"
              :key="index"
              :class="{' mui-active': index === 0}"
              :href="`#${item.id}`"
              @tap="initData(item)"
              class="mui-control-item notice-nav-a"
            >
              {{ item.name }}
              <span v-show="item.code=='WD'&&noReadCount!='0'">({{ noReadCount }})</span>
            </a>
          </div>
        </div>

        <div class="mui-slider-group">
          <div
            v-for="({ id }, index) in nav_list"
            :id="id"
            :key="index"
            :class="{' mui-active': index === 0}"
            class="mui-slider-item mui-control-content"
            style="border:0px;background: #FFFFFF;"
          >
            <div class="mui-scroll-wrapper list">
              <div class="mui-scroll">
                <ul class="mui-table-view">
                  <li v-for="(item, index) in listData[id]" :key="index">
                    <div @tap="noticeView(item)">
                      <div style="display: flex;">
                        <div class="notice-left">
                          <p>{{ item.USERMSG_BT }}</p>
                        </div>
                        <div class="notice-right">
                          <p>{{ item.SY_CREATEUSERNAME }}</p>
                          <span>{{ item.USERMSG_TIME }}</span>
                        </div>
                      </div>
                      <div>
                        <span v-html="item.USERMSG_NR" />
                      </div>
                    </div>
                    <div v-if="item.flagType" style="display:flex; margin: 5px 0;">
                      <div style="width:80%;" />
                      <button
                        @tap="clickNotice(item,checkData, id)"
                        class="delay mui-btn je-audio-btn"
                      >标记已读</button>
                    </div>
                  </li>
                </ul>
              </div>
            </div>
            <div v-show="listData[id]&&listData[id].length==0" class="nav_list-nodata">
              <!-- 暂无{{ checkData.type=='01'?'未读':'已读' }}数据 -->
              暂无消息通知
            </div>
            <p
              v-show="readShow(id,listData[id])"
              @tap="readAll()"
              class="nav_list-readall jeicon jeicon-broom-o"
            />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Header from '@/components/header';
import isEmpty from 'lodash/isEmpty';
import Code from './class/Code';
export default {
  name: 'Notice',
  components: {
    Header,
  },
  data() {
    return {
      nav_list: [
        {
          name: '未读消息',
          type: '01',
          id: 'item1mobile',
          code: 'WD',
        },
        {
          name: '已读消息',
          type: '02',
          id: 'item2mobile',
          code: 'YD',
        },
      ],
      listData: {},
      checkData: {},
      currentPage: 1,
      flagType: true,
      noReadCount: 0,
      defaultType: 0,
      pullRefreshWrapper: [],
      totalCount: 0,
    }
  },
  computed: {
    userId() {
      return JE.getCurrentUser().id
    },
  },
  created() {
    const that = this
    that.initNavData()
    JE.registBadge((badges, refreshList) => {
      if (refreshList.length == 0) return false
      refreshList.forEach((item) => {
        if (item.code === 'JE-PLUGIN-IM' && item.type === 'MSG') {
          // 执行页面刷新
          that.initRefresh()
        }
      })
    })
  },
  mounted() {
    // this.initRefresh();
    const that = this
    // 阻尼系数
    mui('.mui-scroll-wrapper.list').scroll({
      bounce: false,
      scrollX: false,
      scrollY: true,
      indicators: false,
    })
    document.addEventListener('detailBack', (e) => {
      that.defaultType = e.detail.type
      that.initNavData()
    })
  },
  methods: {
    noticeView(item) {
      // 根据是否存在USERMSG_APPINFO，存在-->插件跳转，不存在---> 组件内页面跳转
      if (item.USERMSG_APPINFO) {
        var { funcCode } = JSON.parse(item.USERMSG_APPINFO)[0]
        var { pkValue } = JSON.parse(item.USERMSG_APPINFO)[0].params
      } else {
        var funcCode = ''
      }

      if (funcCode) {
        JE.showFunc(funcCode, {
          funcCode:funcCode,
          pkValue: pkValue
        })
      } else {
        this.$router.push({
          path: '/JE-PLUGIN-NOTICE/noticeDetail',
          query: {
            id: item.JE_SYS_USERMSG_ID
          },
        });
        // openWindow({
        //   url: 'pages_noticeDetail_index.html',
        //   id: `_notice_detail${item.SY_CREATEUSERID}`,
        //   title: '通知详情',
        //   extras: {
        //     noticeItem: item,
        //   },
        // })
      }
    },
    isEmpty,
    // 加载导航栏的数据
    async initNavData() {
      await this.initData(this.nav_list[0])
      this.$nextTick(() => {
        this.initRefresh()
        mui('#sliderSegmentedControl').scroll({
          bounce: true,
          indicators: false,
        })
      })
    },
    initData(item) {
      // 当前选中的模块的数据
      this.checkData = item
      const { id, code } = item
      const params = {
        startTime: '',
        endTime: '',
        start: 0,
        limit: 10,
        readStatus: code,
        tableCode: 'JE_SYS_USERMSG',
        orderSql: 'ORDER BY SY_CREATETIME DESC',
        whereSql: `AND USERMSG_JSR_ID='${
          this.userId
        }' AND USERMSG_MSGTYPE_CODE IN ('MSG','WY','WF') AND USERMSG_YD = '${
          code == 'WD' ? 0 : 1
        }'`,
        j_query: JSON.stringify({
          custom: [
            {
              code: 'USERMSG_JSR_ID',
              type: '=',
              value: this.userId,
            },
            {
              code: 'USERMSG_MSGTYPE_CODE',
              type: 'in',
              value: [
                'MSG',
                'WY',
              ],
            },
            {
              code: 'USERMSG_YD',
              type: '=',
              value: code == 'WD' ? 0 : 1,
            },
          ],
          order: [
            {
              code: 'SY_CREATETIME',
              type: 'desc',
            },
          ],
        }),
      }
      return Code.getNoticeNumbers(params).then((data) => {
        const getNoticeNumbers = data
        this.noReadCount = getNoticeNumbers.noReadCount
        this.totalCount = getNoticeNumbers.totalCount
        // 转载数据
        this.$set(this.listData, id, [
          ...data.rows.map(
            ({
              USERMSG_BT,
              USERMSG_NR,
              SY_CREATEUSERNAME,
              USERMSG_TIME,
              USERMSG_APPINFO,
              ...other
            }) => ({
              USERMSG_BT,
              flagType: id == 'item1mobile',
              USERMSG_NR,
              SY_CREATEUSERNAME,
              USERMSG_TIME,
              USERMSG_APPINFO,
              ...other,
            })
          ),
        ])
        mui('.mui-slider').slider()
      })
      // debugger
      // this.initRefresh()
    },
    readShow(id, list) {
      const thatOne = this.nav_list[0].id
      if (id == thatOne && list && list.length > 0) {
        return true
      }
      return false
    },
    // 全部已读
    readAll() {
      const that = this
      const nums = this.listData.item1mobile.length
      const btnArray = ['取消', '确定']
      mui.confirm('是否全部设为已读？', '提示', btnArray, async (e) => {
        if (e.index === 1) {
          const readAllBack = await Code.readAll()
          if (readAllBack.success) {
            // JE.refreshBadge({
            //   badge: -nums,
            //   apkBadge: -nums,
            //   code: 'JE-PLUGIN-IM',
            //   type: 'MSG',
            // })
            that.initNavData()
            // const targetWebview = plus.webview.getWebviewById('JE-PLUGIN-IM')
            // mui.fire(targetWebview, 'noticeReadAll', {
            //   count: 0,
            // })
          } else {
            mui.toast(readAllBack.obj)
          }
        }
      })
    },
    // 标记已读
    async clickNotice(item, checkData, id) {
      if (checkData.code == 'WD') {
        const index_ = this.listData[id].findIndex(
          (data) => data.JE_SYS_USERMSG_ID == item.JE_SYS_USERMSG_ID
        )
        setTimeout(() => {
          this.listData[id].splice(index_, 1)
          this.noReadCount -= 1
        }, 1000)
        JE.refreshBadge({
          badge: -1,
          apkBadge: -1,
          code: 'JE-PLUGIN-IM',
          type: 'MSG',
        })
        const params = {
          tableCode: 'JE_SYS_USERMSG',
          JE_SYS_USERMSG_ID: item.JE_SYS_USERMSG_ID,
          USERMSG_YD: '1',
        }
        // 消息角标数量发送监听
        const noticeObj = await Code.getNoticeReads(params)
        // if (Object.keys(noticeObj).length) {
        //   const targetWebview = plus.webview.getWebviewById('JE-PLUGIN-IM')
        //   mui.fire(targetWebview, 'noticeRead', this.currentItem)
        //   mui.toast('已读')
        // }
      }

      return false
      // openWindow({
      //   url: 'pages_noticeDetail_index.html',
      //   id: `_notice_detail${item.SY_CREATEUSERID}`,
      //   title: '通知详情',
      //   extras: {
      //     noticeItem: item,
      //     selectedType: checkData.code == 'WD' ? 0 : 1,
      //   },
      // })
    },
    // 循环初始化所有下拉刷新，上拉加载。
    initRefresh() {
      const that = this
      mui('.mui-slider').slider()
      const pullRefreshWrapper = Array.from(
        document.querySelectorAll('.mui-scroll-wrapper.list')
      )
      this.pullRefreshWrapper = pullRefreshWrapper.map((pullRefreshEl) =>
        mui(pullRefreshEl).pullRefresh4HTML({
          // 下拉刷新
          down: {
            async callback() {
              const self = this
              await that.initData(that.checkData)
              if (that.totalCount <= 10) {
                self.endPulldownToRefresh(true)
              } else {
                self.endPulldownToRefresh()
              }
              that.currentPage = 1
              mui.toast('刷新成功')
              self.refresh(true)
            },
          },
          // 上拉加载
          up: {
            auto: false,
            offset: 1000, // 距离底部高度(到达该高度即触发)
            show: true,
            contentinit: '上拉显示更多',
            contentdown: '上拉显示更多',
            contentrefresh: '正在加载...',
            contentnomore: '没有更多数据了',
            async callback() {
              const self = this
              const checkTypeId = that.checkData.id
              const { id, code } = that.checkData
              that.currentPage++
              const paramObj = {
                startTime: '',
                endTime: '',
                start: that.currentPage * 10 - 10,
                limit: 10,
                readStatus: code,
                tableCode: 'JE_SYS_USERMSG',
                orderSql: 'ORDER BY SY_CREATETIME DESC',
                whereSql: `AND USERMSG_JSR_ID='${
                  that.userId
                }' AND USERMSG_MSGTYPE_CODE IN ('MSG','RZ','RC','XSSLH','XS','XSXS','KH','GH','HTHK','WY') AND USERMSG_YD = '${
                  code == 'WD' ? 0 : 1
                }'`,
              }
              const getNoticeNumbers = await Code.getNoticeNumbers(paramObj)
              if (getNoticeNumbers.success == false) {
                mui.toast('数据查询失败')
                return false
              }
              const { rows } = getNoticeNumbers
              const flagType = id == 'item1mobile'
              rows.forEach((item) => {
                item.flagType = flagType
              })
              //   // 禁用上拉加载
              if (that.currentPage > 1) {
                const bottomtips = document
                  .getElementById(checkTypeId)
                  .getElementsByClassName('mui-pull')
                if (bottomtips != '' && bottomtips != undefined) {
                  bottomtips[1].style.display = ''
                }
              }

              if (rows.length < 10) {
                self.endPullupToRefresh(true)
                if (that.currentPage == 2) {
                  const bottomtips = document
                    .getElementById(checkTypeId)
                    .getElementsByClassName('mui-pull')
                  if (bottomtips != '' && bottomtips != undefined) {
                    bottomtips[1].style.display = 'none'
                  }
                }
                return false
              }
              self.endPullupToRefresh(false)
              // 数据拼接
              that.$set(
                that.listData,
                checkTypeId,
                that.listData[checkTypeId].concat(rows)
              )
            },
          },
        })
      )
      // 左右滑动
      document
        .getElementById('slider')
        .addEventListener('slide', async ({ detail: { slideNumber } }) => {
          const num = slideNumber + 1
          // 根据滑动的type获取选中nav的数据
          const type = `0${num}`
          let item
          if (type == '01') {
            this.flagType = true
          } else if (type == '02') {
            this.flagType = false
          }
          that.nav_list.forEach((list) => {
            if (list.type === type) {
              item = list
            }
          })
          this.checkData = item
          this.currentPage = 1
          await that.initData(item)
          const currentPullRefresh = this.pullRefreshWrapper[slideNumber]
          currentPullRefresh.refresh(true)
          mui(currentPullRefresh.element.parentNode).scroll().refresh()
          const bottomtips = document
            .getElementById(this.checkData.id)
            .getElementsByClassName('mui-pull')
          bottomtips[1].style.display = 'none'
        })
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@/theme/index.less';

.nav_list-nodata {
  width: 100%;
  margin-top: 50%;
  text-align: center;
  font-size: 20 * @hd;
  color: #bebebe;
}

.nav_list-readall {
  position: fixed;
  z-index: 2;
  bottom: 80 * @hd;
  right: 40 * @hd;
  background: #536dfe;
  border-radius: 50%;
  width: 50 * @hd;
  height: 50 * @hd;
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 22 * @hd;
  z-index: 100;

  &:active {
    background: #3c56e3;
  }
}

.notice {
  .notice-nav {
    color: #3f3f3f;
    font-size: 16 * @hd;
    height: 44 * @hd;
    background: #ffffff;

    .notice-nav-a {
      font-size: 16 * @hd;
      border-bottom: 1px solid transparent;
      height: 42 * @hd;
      line-height: 42 * @hd;
    }
  }

  .notice-title {
    line-height: 22 * @hd;
    font-size: 16 * @hd;
    color: #3f3f3f;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    overflow: hidden;
  }

  .notice-title-circle {
    width: 4 * @hd;
    height: 4 * @hd;
    background: rgba(255, 61, 61, 1);
    border-radius: 50%;
    display: inline-block;
    margin-top: 3 * @hd;
    margin-right: 4 * @hd;
  }

  .notice-info {
    font-size: 14 * @hd;
    color: #a9aba9;
    font-weight: 400;
    margin-top: 12 * @hd;
  }

  .mui-table-view-cell {
    display: flex;
    padding: 15 * @hd 15 * @hd;

    .notice-left {
      flex: 1;
    }

    &:after {
      background-color: #f5f5f5;
      height: 2 * @hd;
    }
  }
}
</style>
<style lang="less">
@import '~@/theme/index.less';

html,
body {
  background-color: #f8f8f8 !important;
}

.delay {
  background-color: #536dfe;
  border-color: #536dfe;
  color: #ffffff;
  padding: 4px 5px;
  height: 25 * @hd;
  float: right;
  width: 20%;
}

.mui-bar ~ .mui-content .mui-fullscreen {
  // top: 44 * @hd;
  top: unit(45 * @hd, px);
  height: auto;
}
.mui-fullscreen {
  top: unit(45 * @hd, px) !important;
}
.mui-pull-top-tips {
  position: absolute;
  top: -20 * @hd;
  left: 50%;
  margin-left: -25 * @hd;
  width: 40 * @hd;
  height: 40 * @hd;
  border-radius: 100%;
  z-index: 1;
}

.mui-bar ~ .mui-pull-top-tips {
  top: 24 * @hd;
}

.mui-pull-top-wrapper {
  width: 42 * @hd;
  height: 42 * @hd;
  display: block;
  text-align: center;
  background-color: #efeff4;
  border: 1 * @hd solid #ddd;
  border-radius: 25 * @hd;
  background-clip: padding-box;
  box-shadow: 0 4 * @hd 10 * @hd #bbb;
  overflow: hidden;
}

.mui-pull-top-tips.mui-transitioning {
  -webkit-transition-duration: 200ms;
  transition-duration: 200ms;
}

.mui-pull-top-tips .mui-pull-loading {
  /*-webkit-backface-visibility: hidden;
      -webkit-transition-duration: 400ms;
      transition-duration: 400ms;*/

  margin: 0;
}

.mui-pull-top-wrapper .mui-icon,
.mui-pull-top-wrapper .mui-spinner {
  margin-top: 7 * @hd;
}

.mui-pull-top-wrapper .mui-icon.mui-reverse {
  /*-webkit-transform: rotate(180deg) translateZ(0);*/
}

.mui-pull-bottom-tips {
  text-align: center;
  background-color: #efeff4;
  font-size: 15 * @hd;
  line-height: 40 * @hd;
  color: #777;
}

.mui-pull-top-canvas {
  overflow: hidden;
  background-color: #fafafa;
  border-radius: 40 * @hd;
  box-shadow: 0 4 * @hd 10 * @hd #bbb;
  width: 40 * @hd;
  height: 40 * @hd;
  margin: 0 auto;
}

.mui-pull-top-canvas canvas {
  width: 40 * @hd;
}

.mui-slider-indicator.mui-segmented-control {
  background-color: #ffffff;
}

// 修改tab标签高度
.mui-segmented-control.mui-scroll-wrapper {
  height: 45 * @hd;
}

.mui-slider
  .mui-segmented-control.mui-segmented-control-inverted
  .mui-control-item.mui-active {
  border-bottom: 1px solid #007aff !important;
}

.mui-fullscreen .mui-segmented-control ~ .mui-slider-group {
  top: 94px;
}

.mui-scrollbar {
  display: none !important;
}

li {
  /* display: flex; */
  justify-content: space-between;
  padding: 5px 0px;
  margin: 0 10px;
  border-bottom: 1px solid #faf7f7;

  .notice-left {
    width: 80%;

    p {
      padding-bottom: 5px;
    }

    p,
    span {
      width: 100%;
      display: block;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
    }
  }

  .notice-right {
    width: 30%;

    span {
      text-align: right;
      font-size: 24px !important;
    }

    p {
      text-align: right;
      padding-bottom: 5px;
    }
  }

  p {
    font-size: 32px;
    font-weight: 400;
    color: rgba(63, 63, 63, 1);
    line-height: 44px;
  }

  span {
    font-size: 28px;
    font-weight: 400;
    color: rgba(169, 171, 169, 1);
    line-height: 40px;
    display: block;
  }
}
</style>